package com.example.controller;

import com.example.common.Result;
import com.example.entity.Product;
import com.example.entity.User;
import com.example.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品控制器
 * @author System
 * @date 2024
 */
@Controller
@RequestMapping("/product")
public class ProductController {
    
    private static final Logger logger = LoggerFactory.getLogger(ProductController.class);
    
    @Autowired
    private ProductService productService;
    
    /**
     * 添加商品（管理员功能）
     */
    @PostMapping("/add")
    @ResponseBody
    public Result addProduct(@RequestBody Product product, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 简单的权限检查（这里假设用户名为admin的是管理员）
            if (!"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }
            
            // 参数验证
            if (product == null || product.getName() == null || product.getPrice() == null) {
                return Result.badRequest("参数不完整");
            }
            
            // 检查商品名称是否已存在
            if (productService.isProductExists(product.getName())) {
                return Result.error("商品名称已存在");
            }
            
            boolean success = productService.addProduct(product);
            if (success) {
                logger.info("添加商品成功: {}", product.getName());
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            logger.error("添加商品异常", e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 根据ID查询商品
     */
    @GetMapping("/{id}")
    @ResponseBody
    public Result getProductById(@PathVariable Long id) {
        try {
            Product product = productService.getProductById(id);
            if (product != null) {
                return Result.success("查询成功", product);
            } else {
                return Result.notFound("商品不存在");
            }
        } catch (Exception e) {
            logger.error("查询商品异常: id={}", id, e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 查询所有商品
     */
    @GetMapping("/list")
    @ResponseBody
    public Result getAllProducts() {
        try {
            List<Product> products = productService.getAllProducts();
            return Result.success("查询成功", products);
        } catch (Exception e) {
            logger.error("查询所有商品异常", e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 查询可用商品（已上架）
     */
    @GetMapping("/available")
    @ResponseBody
    public Result getAvailableProducts() {
        try {
            List<Product> products = productService.getAvailableProducts();
            return Result.success("查询成功", products);
        } catch (Exception e) {
            logger.error("查询可用商品异常", e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 分页查询商品
     */
    @GetMapping("/page")
    @ResponseBody
    public Result getProductsByPage(@RequestParam(defaultValue = "1") int page,
                                   @RequestParam(defaultValue = "10") int size,@RequestParam(required = false) String category) {
        try {
            List<Product> products = productService.getProductsByPage(page, size,category);
            int total = productService.getProductCount(category);
            
            // 构建分页结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", products);
            result.put("total", total);
            result.put("page", page);
            result.put("size", size);
            result.put("pages", (total + size - 1) / size);
            
            return Result.success("查询成功", result);
        } catch (Exception e) {
            logger.error("分页查询商品异常: page={}, size={}", page, size, e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 根据分类查询商品
     */
    @GetMapping("/category/{category}")
    @ResponseBody
    public Result getProductsByCategory(@PathVariable String category) {
        try {
            List<Product> products = productService.getProductsByCategory(category);
            return Result.success("查询成功", products);
        } catch (Exception e) {
            logger.error("根据分类查询商品异常: category={}", category, e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 根据关键词搜索商品
     */
    @GetMapping("/search")
    @ResponseBody
    public Result searchProducts(@RequestParam String keyword) {
        try {
            List<Product> products = productService.getProductsByKeyword(keyword);
            return Result.success("搜索成功", products);
        } catch (Exception e) {
            logger.error("搜索商品异常: keyword={}", keyword, e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 更新商品信息（管理员功能）
     */
    @PutMapping("/update")
    @ResponseBody
    public Result updateProduct(@RequestBody Product product, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 简单的权限检查
            if (!"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }
            
            if (product == null || product.getId() == null) {
                return Result.badRequest("参数不完整");
            }
            
            boolean success = productService.updateProduct(product);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            logger.error("更新商品异常", e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 更新商品状态（管理员功能）
     */
    @PutMapping("/status")
    @ResponseBody
    public Result updateProductStatus(@RequestBody Map<String, Object> params, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 简单的权限检查
            if (!"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }
            
            Long productId = Long.valueOf(params.get("productId").toString());
            Integer status = Integer.valueOf(params.get("status").toString());
            
            boolean success = productService.updateProductStatus(productId, status);
            if (success) {
                return Result.success("状态更新成功");
            } else {
                return Result.error("状态更新失败");
            }
        } catch (Exception e) {
            logger.error("更新商品状态异常", e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 更新商品库存（管理员功能）
     */
    @PutMapping("/stock")
    @ResponseBody
    public Result updateProductStock(@RequestBody Map<String, Object> params, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 简单的权限检查
            if (!"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }
            
            Long productId = Long.valueOf(params.get("productId").toString());
            Integer stock = Integer.valueOf(params.get("stock").toString());
            
            boolean success = productService.updateProductStock(productId, stock);
            if (success) {
                return Result.success("库存更新成功");
            } else {
                return Result.error("库存更新失败");
            }
        } catch (Exception e) {
            logger.error("更新商品库存异常", e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 删除商品（管理员功能）
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public Result deleteProduct(@PathVariable Long id, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 简单的权限检查
            if (!"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }
            
            boolean success = productService.deleteProduct(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            logger.error("删除商品异常: id={}", id, e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 批量删除商品（管理员功能）
     */
    @DeleteMapping("/batch")
    @ResponseBody
    public Result deleteProducts(@RequestBody List<Long> ids, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 简单的权限检查
            if (!"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }
            
            if (ids == null || ids.isEmpty()) {
                return Result.badRequest("请选择要删除的商品");
            }
            
            boolean success = productService.deleteProducts(ids);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            logger.error("批量删除商品异常", e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 获取商品统计信息（管理员功能）
     */
    @GetMapping("/stats")
    @ResponseBody
    public Result getProductStats(HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 简单的权限检查
            if (!"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("total", productService.getProductCount());
            stats.put("available", productService.getProductCountByStatus(1));
            stats.put("unavailable", productService.getProductCountByStatus(0));
            
            return Result.success("查询成功", stats);
        } catch (Exception e) {
            logger.error("获取商品统计信息异常", e);
            return Result.error("系统异常");
        }
    }
    @GetMapping("/count")
    @ResponseBody
    public Result count() {
        try {
            return Result.success( productService.getProductCount());
        } catch (Exception e) {
            return Result.error("系统异常");
        }
    }
    @GetMapping("/categories")
    @ResponseBody
    public Result categories() {
        try {
            return Result.success( productService.getCategories());
        } catch (Exception e) {
            return Result.error("系统异常");
        }
    }
}